<template>
    <div style="padding-left: 20px">
        <el-row :gutter="10">
            <el-col :span="1.5">
                <el-button type="primary" plain @click="handleAdd" v-hasPermi="['iot:thingsModel:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" @click="handleImport" plain>导入通用物模型</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" @click="handleQuery" plain>刷新</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="info" @click="handleOpenThingsModel" plain>查看物模型</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-link type="danger" style="padding-top: 5px" :underline="false">注意：标识符不能重复</el-link>
            </el-col>
        </el-row>
        <el-table :data="thingsModelList" border style="width: 100%;padding-top: 8px;">
            <el-table-column label="物模型ID" width="180" align="center" prop="modelId" v-if="false" />
            <el-table-column label="名称" width="180" align="center" prop="modelName" />
            <el-table-column label="标识符" width="180" align="center" prop="identifier" />
            <el-table-column label="图表展示" width="180" align="center" prop="isChart">
                <template #default="scope">
                    <dict-tag :options="iot_yes_no" :value="scope.row.isChart" />
                </template>
            </el-table-column>
            <el-table-column label="实时监测" width="180" align="center" prop="isMonitor">
                <template #default="scope">
                    <dict-tag :options="iot_yes_no" :value="scope.row.isMonitor" />
                </template>
            </el-table-column>
            <el-table-column label="只读" width="180" align="center" prop="isReadonly">
                <template #default="scope">
                    <dict-tag :options="iot_yes_no" :value="scope.row.isReadonly" />
                </template>
            </el-table-column>
            <el-table-column label="历史存储" width="180" align="center" prop="isHistory">
                <template #default="scope">
                    <dict-tag :options="iot_yes_no" :value="scope.row.isHistory" />
                </template>
            </el-table-column>
            <el-table-column label="模型类别" width="180" align="center" prop="type">
                <template #default="scope">
                    <dict-tag :options="iot_type" :value="scope.row.type" />
                </template>
            </el-table-column>
            <el-table-column label="数据类型" width="180" align="center" prop="datatype">
                <template #default="scope">
                    <dict-tag :options="iot_data_type" :value="scope.row.datatype" />
                </template>
            </el-table-column>
            <!-- <el-table-column label="数据定义" width="180" align="center" prop="specs" /> -->
            <el-table-column label="数据定义" align="left" header-align="center" prop="specs" min-width="180"
                class-name="specsColor">
                <template #default="scope">
                    <div v-html="formatSpecsDisplay(scope.row.specs, scope.row.datatype)"></div>
                </template>
            </el-table-column>
            <el-table-column prop="date" width="180" label="计算公式" />
            <el-table-column label="排序" width="180" align="center" prop="modelOrder" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-tooltip content="修改" placement="top">
                        <el-button link type="primary" @click="handleUpdate(scope.row)" icon="Edit"
                            v-hasPermi="['iot:thingsModel:edit']"></el-button>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                            v-hasPermi="['iot:thingsModel:remove']"></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />
        <!--物模型参数类型-->
        <product-add :get-list="getList" ref="productAddRef"></product-add>

        <!-- 导入通用物模型对话框 -->
        <el-dialog :title="dialogModel.title" v-model="dialogModel.open" width="800px" destroy-on-close append-to-body>
            <product-select-template ref="productSelectTemplate" />
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleImportSubmit">导 入</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 物模型JSON -->
        <el-dialog :title="dialogModeljson.title" v-model="dialogModeljson.open" width="600px" append-to-body>
            <div style="border: 1px solid #ccc; margin-top: -15px; height: 600px; overflow: scroll">
                <json-viewer :value="thingsModelList" :expand-depth="10" copyable>
                    <template v-slot:copy>复制</template>
                </json-viewer>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="info" @click="handleCloseThingsModel">关 闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import productAdd from './product-add.vue'
import { listThingsModel, listThingsModelByProductId, delThingsModel } from '@/api/iot/thingsModel';
import { ThingsModelVO, ThingsModelQuery, ThingsModelForm ,ThingsModelQueryData} from '@/api/iot/thingsModel/types';
import ProductSelectTemplate from './product-select-template.vue'
import JsonViewer from 'vue-json-viewer'
import 'vue-json-viewer/style.css';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { iot_yes_no, iot_type, iot_data_type } = toRefs<any>(proxy?.useDict('iot_yes_no', 'iot_type', 'iot_data_type'));
/**
 * 物模型标题和是否显示弹框
 */
const dialogModel = reactive({
    title: '',
    open: false
});

/**
 * 查看物模型标题和是否显示弹框
 */
const dialogModeljson = reactive({
    title: '查看物模型',
    open: false
});
const thingsModelList = ref<ThingsModelVO[]>([]);
const loading = ref(true);
const ids = ref<Array<string | number>>([]);
const total = ref(0);
const props = defineProps(['productId'])
const initFormData: ThingsModelForm = {
}

const thingsModelQueryData: ThingsModelQueryData = {
    productId: props.productId
}

const data = reactive<PageData<ThingsModelForm, ThingsModelQuery>>({
    form: { ...initFormData },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: props.productId,
        params: {
        }
    },
    rules: {
    }
});

const { queryParams } = toRefs(data);

//定义对子组件的引用
const productAddRef = ref<InstanceType<typeof productAdd> | null>(null)
/** 新增按钮操作 */
const handleAdd = () => {
    if (productAddRef.value && productAddRef.value.dialog) {
        productAddRef.value.dialog.visible = true
        productAddRef.value.dialog.title = '添加物模型'
    } else {
        console.error('无法获取子组件引用或dialog对象')
    }
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ThingsModelVO) => {
    if (productAddRef.value && productAddRef.value.dialog) {
        console.log("hhhhhh==" + row.modelId)
        productAddRef.value.dialog.visible = true
        productAddRef.value.dialog.title = '修改物模型'
        productAddRef.value.getThingsModelById(row.modelId);
    } else {
        console.error('无法获取子组件引用或dialog对象')
    }
}



onMounted(() => {
    console.log("hhhhhh")
    getList();
});
/** 查询物模型列表 */
const getList = async () => {
    loading.value = true;
    const res = await listThingsModel(queryParams.value);
    thingsModelList.value = res.rows;
    total.value = res.total;
    loading.value = false;
}

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
}
// 定义对子组件的引用
const productSelectTemplate = ref<InstanceType<typeof ProductSelectTemplate> | null>(null)
/**
 * 导入通用物模型
 */
const handleImport = () => {
    dialogModel.title = '导入通用物模型';
    dialogModel.open = true;
    nextTick(() => {
        if (productSelectTemplate.value && typeof productSelectTemplate.value.getList === 'function') {
            productSelectTemplate.value.getList();
        }
    });
}
//导入按钮事件
const handleImportSubmit = () => {
    console.log(productSelectTemplate)
    nextTick(() => {
        if (productSelectTemplate.value && typeof productSelectTemplate.value.daoru === 'function') {
            console.log(productSelectTemplate.value.ids);
            const importData = {
                productId: productSelectTemplate.value.productIdAdd,
                productName: productSelectTemplate.value.productNameAdd,
                templateIds: productSelectTemplate.value.ids
            }
            productSelectTemplate.value.daoru(importData);
        }

    });


}
/** 取消按钮 */
const cancel = () => {
    dialogModel.open = false;
}
/** 查看物模型按钮操作 */
const handleOpenThingsModel = async () => {
    const res = await listThingsModelByProductId(thingsModelQueryData);
    thingsModelList.value = res.data;
    dialogModeljson.open = true;
}
/** 关闭物模型json弹框 */
const handleCloseThingsModel = () => {
    dialogModeljson.open = false;
}
/** 删除按钮操作 */
const handleDelete = async (row?: ThingsModelVO) => {
    const _modelIds = row?.modelId || ids.value;
    await proxy?.$modal.confirm('是否确认删除模型编号为"' + _modelIds + '"的数据项？').finally(() => loading.value = false);
    await delThingsModel(_modelIds);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
}
/** 格式化显示数据定义 */
const formatSpecsDisplay = (json, number) => {
    console.log(number);
    if (json == null || json == undefined) {
        return;
    }
    let specs = JSON.parse(json);
    if (number === '1' || number === '2') {
        return (
            '<span style=\'width:50%;display:inline-block;\'>最大值：<span style="color:#F56C6C">' +
            specs.max +
            '</span></span>最小值：<span style="color:#F56C6C">' +
            specs.min +
            '</span><br /><span style=\'width:50%;display:inline-block;\'>步长：<span style="color:#F56C6C">' +
            specs.step +
            '</span></span>单位：<span style="color:#F56C6C">' +
            specs.unit
        );
    } else if (number === '3') {
        return '最大长度：<span style="color:#F56C6C">' + specs.maxLength + '</span>';
    } else if (number === '5') {
        return '<span style=\'width:50%;display:inline-block;\'>数组类型：<span style="color:#F56C6C">' + specs.arrayType + '</span></span>元素个数：<span style="color:#F56C6C">' + specs.arrayCount;
    } else if (number === '6') {
        let items = '';
        for (let i = 0; i < specs.enumList.length; i++) {
            items = items + "<span style='width:50%;display:inline-block;'>" + specs.enumList[i].value + "：<span style='color:#F56C6C'>" + specs.enumList[i].text + '</span></span>';
            if (i > 0 && i % 2 != 0) {
                items = items + '<br />';
            }
        }
        return items;
    } else if (number === '4') {
        return '<span style=\'width:50%;display:inline-block;\'>0：<span style="color:#F56C6C">' + specs.falseText + '</span></span>1：<span style="color:#F56C6C">' + specs.trueText;
    } else if (number === '7') {
        let items = '';
        for (let i = 0; i < specs.params.length; i++) {
            items = items + "<span style='width:50%;display:inline-block;'>" + specs.params[i].name + "：<span style='color:#F56C6C'>" + specs.params[i].datatype.type + '</span></span>';
            if (i > 0 && i % 2 != 0) {
                items = items + '<br />';
            }
        }
        return items;
    }
};
</script>
<style lang="scss" scoped></style>